package com.hxh.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.hxh.dao.ProjectDao;
import com.hxh.dao.ProjectDatasourceDao;
import com.hxh.dao.ProjectDetailDao;
import com.hxh.entity.Project;
import com.hxh.entity.ProjectDetail;
import com.hxh.entity.input.ProjectInput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;


@Service
@Transactional
@Slf4j
public class ProjectService {
    @Resource
    ProjectDao projectDao;

    @Resource
    ProjectDetailDao projectDetailDao;

    @Resource
    ProjectConfigRecordService projectConfigRecordService;

    @Resource
    ProjectDatasourceDao projectDatasourceDao;

    public boolean insertAll(Project pojo, ProjectDetail backendProject, ProjectDetail frontendProject) {
        boolean res = projectDao.insert(pojo) > 0;
        if (res) {
            backendProject.setProjectId(pojo.getId());
            res = projectDetailDao.insert(backendProject) > 0;
        }
        if (res) {
            frontendProject.setProjectId(pojo.getId());
            res = projectDetailDao.insert(frontendProject) > 0;
        }
        return res;
    }

    public boolean updateAll(Project pojo, ProjectDetail backendProject, ProjectDetail frontendProject) {
        boolean res = projectDao.update(pojo) > 0;
        if (res) {
            res = projectDetailDao.update(backendProject) > 0;
        }
        if (res) {
            res = projectDetailDao.update(frontendProject) > 0;
        }
        return res;
    }


    public boolean deleteAll(int id) {
        boolean res = projectDao.deleteById(id) > 0;
        if (res) {
            res = projectDetailDao.deleteByProjectId(id) > 0;
            projectConfigRecordService.deleteById(id);
        }
        return res;
    }

    public int insertList(List<ProjectInput> pojo) {
        if (CollectionUtils.isEmpty(pojo)) {
            return 0;
        }

        int res = projectDao.insertList(pojo);
        return res;
    }

    public List<Project> select(ProjectInput pojo) {
        return projectDao.select(pojo);
    }

    public List<Project> selectByDatasourceId(Integer datasourceId) {
        return projectDao.selectByDatasourceId(datasourceId);
    }

    public boolean deleteById(Integer id) {
        return projectDao.deleteById(id) > 0;
    }

    public Project selectById(Integer id) {
        if (id == null) {
            return null;
        }
        return projectDao.selectById(id);
    }

    public void listPage(Page<Project> page, ProjectInput pojo) {
        List<Project> projects = projectDao.listPage(page, pojo);
        page.setRecords(projects);
    }


}
